require "Common/define"
require "Logic/Config"
require "Net/send_Msg"
require "Net/roleListHandler"
require "Net/itemHandler"
require "Common/functions"
require "proto/dungeon/message/ReqBossMessage"
require "proto/dungeon/message/ReqGroupBossMessage"
require "proto/player/message/ReqSettleMessage"
require "proto/dungeon/message/ReqHardDungeonInfoMessage"
require "proto/dungeon/message/ReqHardDungeonRushMessage"

--require "Battle/BattleScene"
require "FairyGUI"
require "Net/FriendBattleHandler"
local UIBattleBGMap = require "View/BattleUI/UIBattleBGMap"
local UIBattleBGMap1 = require "View/BattleUI/UIBattleBGMap1"
require "View/BattleUI/SubPanel/UIBattleRobListPanel"
UIBattle = {};
HelperFunc.SetUIEnv(UIBattle)
local this = UIBattle;

function UIBattle.InitLocalData()
    this.msg_type = Config.msg_type
    
    this.LuaBehaviour = nil;
    this.transform = nil;
    this.gameObject = nil;

    this.btn_boss = nil;
    this.btn_boss2 = nil;
    this.btn_chat = nil;
    this.btn_quick = nil;
    this.btn_dropInfo = nil;
    this.btn_story = nil;
    this.btn_map = nil;
    this.btn_reward = nil;
    this.spineStageIdel = nil;
    this.spineStageEffect = nil;
    this.spineDrop = nil;

    this.lab_exp = nil;
    this.lab_money = nil;
    this.shadow = nil;

    this.lastSyncTime = 0;
    this.mapType = 0;
    this.mapId = 0;
    this.onlineTimer = nil;

    this.turntable = nil;--指针组件
    this.aniLevel = nil;
    --this.txtCurLevel = nil;
    --this.txtBeforeLevel = nil;
    --this.txtBeforeBeforeLevel = nil;
    --this.txtAfterLevel = nil;
    --this.txtAfterAfterLevel = nil;
    this.btnDetails = nil;
    --this.txtTeame = nil;
    this.leftTransition = nil;
    this.rightTransition = nil;

    this.hasInit = false;
    this.battleMainRoot = nil;
    this.cameraMain = nil;

    this.curMouseXPos = nil;
    this.curMouseYPos = nil;
    this.chatPosX = nil;
    this.chatPosY = nil;
    this.Xoffset = 0;
    this.Yoffset = 0;
    this.btn_team = nil;
    this.inLongClick = false;

    this.stageConfig = nil;
    this.itemConfig = nil;
    this.equipConfig = nil;
    this.aniStageConfig = nil;
    this.curAniIndex = 0;

    this.lastStage = 0; -- 上一次显示关卡的时间
    this.tableTaskInfo = nil;

    this.controllerBoos = nil;
    this.controllerFallInfo = nil;
    this.controllerMapInfo = nil;
    this.controllerMask = nil;

    this.shadowShowAni = nil;
    this.shadowHideAni = nil;
    this.isShowAni = false;
    this.pool = nil;
    this.parPool = nil;
    this.drawWrapper = nil;
    this.spine = nil;
    this.dropParticle = nil;
    this.dropWrap = {};
    this.curChapter = nil;
    this.listPool = {};
    this.listParticle = {};
    this.index = 1;
    this.battleInfo = {};
    this.dropTimer1 = nil
    this.dropTimer2 = nil
    this.carAnim = nil
    this.roleId = nil
    this.friendCtrl = nil
    this.friendList = nil
    this.friendInfo = nil
    this.drawWrapper = nil
    this.drawWrapper1 = nil
    this.posuiWrap = nil
    this.posuiObj = nil
    this.btnIcon = nil
    this.btnChapterReward = nil
    this.btnChapterRewardTips = nil
    this.btnChapterRewardIcon = nil

    this.btnRandomEvent = nil
    this.randomCtrl = nil
    this.TextRandomEventTime = nil
    this.randomEventTimeCount = 0
    this.randomEventTimer = nil
    this.mainReward = nil
end
this.InitLocalData()

function UIBattle.Init()
    

    if this.stageConfig == nil then
        this.stageConfig = G.dataTable["t_stage"];
        this.itemConfig = G.dataTable["t_item"];
        this.equipConfig = dataTable.getDataTable("t_equip");
        this.aniStageConfig = decodeJsonStrToTabel(G.dataTable["t_global"]["87"].f_string_value);
    end
    local name, packageName = getUIName(PanelNames.UIBattle);
    panelMgr:Push(name, packageName, this.onCreate, Config.useLocalUI);
end

function UIBattle.playAudio(chapter)
    local _currentChapterId = logicMgr.MapManager.GetCurrentChapterId()
    if logicMgr.MapManager.isOpenNewChapter() then--处理新章节
        _currentChapterId = _currentChapterId + 1
    end
    if chapter then
        _currentChapterId = chapter
    end

    local chapInfo = G.dataTable["t_Chapter"][tostring(_currentChapterId)]
    if chapInfo then
        AudioManager.Play(chapInfo.f_Bgm)
    end
    AudioManager.Play(19)
end
function UIBattle.stopAudio()
    AudioManager.TryStopAMBSound()
end

--定义控件
function UIBattle.onCreate(obj)
    AddUIPackageDepend("FUI/BattleUI", "FUI/SideGirl")
    AddUIPackageDepend("FUI/BattleUI", "FUI/UILoadingBattle")
    this.mainTaskList = decodeJsonStrToTabel(dataTable.getGlobalString(481)); -- 显示的主线任务类型

    --挂机界面背景音乐
    UIBattle.playAudio()

    gameObject = obj;

    -- 禁用摄像机延迟标记
    delayDisableCamera = false

    shadowShowAni = obj:GetTransition("shadowShow");
    shadowHideAni = obj:GetTransition("shadowHide");

    controllerMask = obj:GetController("mask");--背景控制器 0 on 1 off
    controllerBoos = obj:GetController("boss");--boss警告控制器 0 on 1 off
    --controllerFallInfo = obj:GetController("FallInfo"); -- 掉落信息控制器  0 on 1 off
    controllerMapInfo = obj:GetController("MapInfo"); -- 地图信息控制器  0 on 1 off

    controllerMask.selectedIndex = 1;
    controllerBoos.selectedIndex = 1;
    --controllerFallInfo.selectedIndex = 1;
    controllerMapInfo.selectedIndex = 1;
    --新增剧情模式
    controllerStoryModeOpen = obj:GetController("storyModeOpen"); -- 剧情模式控制器 0 off   1 on
    controllerStoryModeOpen.selectedIndex = 0;
    controllerStoryMode = obj:GetController("storyMode");
    controllerStoryMode.selectedIndex = 0;
    --transform = obj.transform;
    --LuaBehaviour = transform:GetComponent('LuaBehaviour');
    battleMainRoot = panelMgr.BattleMain;

    if not hasInit then
        this.isWaitingBattleFinishedPopUp = false
        hasInit = true;
        if battleMainRoot ~= nil then
            battleMainRoot.gameObject:SetActive(true);
            cameraMain = battleMainRoot.transform:Find("CameraMain"):GetComponent("Camera");
        end

        this.bind = {
            btnCloseWeakness = obj:GetChild("btnCloseWakness"),
            btnWeakness = obj:GetChild("btnWeakness"),
            ctrlWeakness = obj:GetController("sup"),
            ctrlContent = obj:GetController("tips"),
            txtContent1 = obj:GetChild("txtWeakness1"),
            txtContent2 = obj:GetChild("txtWeakness2"),
        }

        mainReward = obj:GetChild("mainReward"):GetChild("list")
        --队伍按钮
        --btn_team = obj:GetChild("TeamBtn");
        --快速战斗按钮
        btn_quick = obj:GetChild("QuickBtn");
        btn_quick.gameObjectName = "QuickBtn";
        --挑战按钮
        btn_boss = obj:GetChild("BossBtn");
        btn_boss2 = obj:GetChild("BossBtn2");
        --聊天按钮（临时）
        btn_chat = obj:GetChild("ChatBtn");
        --阵容推荐
        this.btnBattleRecommend = obj:GetChild("btnBattleRecommend");
        --功能按钮
        --btn_func = obj:GetChild("FuncBtn");
        pool = obj:GetChild("pool");
        parPool = obj:GetChild("parpool");
        --地图按钮
        this.btn_map = obj:GetChild("MapBtn");
        this.ctrlRobOpen = this.btn_map:GetController("Type")
        this.treasureController = this.btn_map:GetController("treasure");
        this.btn_open_map = obj:GetChild("Btn_OpenMap")
        this.txt_cur_stage = obj:GetChild("curstage")
        --挂机收益按钮
        btn_reward = obj:GetChild("RewardBtn");
        --剧情按钮
        --btn_story = obj:GetChild("BtnStory");
        --this.carPanel = UIBattleCarPanel.New()
        --this.carPanel:OnCreate(btn_reward)
        aniLevel = obj:GetTransition("Ani");
        --turntable = obj:GetChild("turntable");
        --txtTeame = obj:GetChild("txtCom");
        leftTransition = obj:GetTransition("t5");
        rightTransition = obj:GetTransition("t6");
        --txtCurLevel = txtTeame:GetChild("CurrentLevel");
        --txtBeforeLevel = txtTeame:GetChild("BeforeLevel");
        --txtBeforeBeforeLevel = txtTeame:GetChild("BeforeBeforeLevel");
        --txtAfterLevel = txtTeame:GetChild("AfterLevel");
        --txtAfterAfterLevel = txtTeame:GetChild("AfterAfterterLevel");
        --txtAfter_level = txtTeame:GetChild("After_level")
        --this.iconCurLevel = txtTeame:GetChild("CurrentIcon");--:GetController("iconType");
        --this.iconBeforeLevel = txtTeame:GetChild("BeforeIcon");--:GetController("iconType");
        --this.iconBeforeBeforeLevel = txtTeame:GetChild("BeforeBeforeIcon");--:GetController("iconType");
        --this.iconAfterLevel = txtTeame:GetChild("AfterIcon");--:GetController("iconType");
        --this.iconAfterAfterLevel = txtTeame:GetChild("AfterAfterterIcon");--:GetController("iconType");
        --this.iconAfter_level = txtTeame:GetChild("After_levelicon")
        this.ctrlNextChapter = obj:GetController("NextChapter")
        ---@type FairyGUI.GLoader3D
        this.eff_zhuanchang_jq = obj:GetChild("eff_zhuanchang_jq")
        this.spineEffectBox = obj:GetChild("Effect_MoTan")
        this.spineEffectBox.skinName = "1"
        this.ctrlMask = obj:GetController("Mask")
        this.collectTipsText = obj:GetChild("collectTipsText")
        this.collectTipsController = obj:GetController("collectTips")
        btnDetails = obj:GetChild("DetailsBtn");
        shadow = obj:GetChild("shadow");
        shadow.visible = false;
        --掉落信息
        --btn_dropInfo = obj:GetChild("BtnDropNew");

        --宠物buff加成
        this.Btn_PetBuff = obj:GetChild("Btn_PetBuff")
        obj:GetChild("Txt_PetBuffAddTitle").text = getLanguage("PetOther_PetEcoBuffAddTitle")
        this.List_PetBuffAdd = obj:GetChild("List_PetBuffAdd")
        this.List_PetBuffAdd.itemRenderer = this.itemRendererPetBuff
        this.PetBuffShowController = obj:GetController("petBuffShow")
        this.Btn_PetBuffClose = obj:GetChild("Btn_PetBuffClose")

        --挂机收益信息
        lab_exp = obj:GetChild("ExpLb");
        lab_money = obj:GetChild("GoldLb");
        curChapter = obj:GetChild("curstage");
        friendCtrl = obj:GetController("friend")
        friendList = obj:GetChild("listFriend")
        --主线推图任务
        this.TaskTitle = obj:GetChild("TaskTitle");
        this.listReward = obj:GetChild("listReward");
        this.taskReceive = obj:GetChild("taskReceive");
        this.nextController = obj:GetController("nextReward");
        --显示主线任务
        this.TaskDesc = obj:GetChild("TaskDesc");
        this.TaskIcon = obj:GetChild("TaskIcon");
        this.TaskReward = obj:GetChild("TaskReward");
        this.taskOpen = obj:GetChild("taskOpen");
        this.taskIcon = obj:GetChild("Icon");
        this.taskIconNum = obj:GetChild("IconNum");
        this.showTaskController = obj:GetController("showTask");
        this.TaskNum = obj:GetChild("TaskNum")
        this.btnChapterReward = obj:GetChild("btnChapterReward");
        this.btnChapterRewardTips = this.btnChapterReward:GetChild("tips");
        this.btnChapterRewardIcon = this.btnChapterReward:GetChild("icon");
        local btnChapterRewardTitle = this.btnChapterReward:GetChild("title");
        btnChapterRewardTitle.text = getLanguage("ChapterRewardText2");
         --新增剧情模式
        this.btnHard = obj:GetChild("btnHard");
        this.btnNormal = obj:GetChild("btnNormal");
        this.btnNormal.text = getLanguage("TeamsStoryModeTips2")
        this.btnHard.text = getLanguage("TeamsStoryModeTips3")
        this.btn_boss2.text = getLanguage("TeamsStoryModeTips1")
        listPool[1] = parPool;
        listPool[2] = pool;

        -- 看板娘
        this.normalSideGirl = obj:GetChild("effect_gjnv")
        this.hardSideGirl = obj:GetChild("effect_hhgjnz")
        this.normalSideGirlOriginPos = {this.normalSideGirl.x, this.normalSideGirl.y}
        this.hardSideGirlOriginPos   = {this.hardSideGirl.x,   this.hardSideGirl.y}

        --shadow = transform:Find("Shadow"):GetComponent("Image");
        this.quickBattleRedDotsName = gameObject.gameObjectName .. btn_quick.gameObjectName;
        --region 掠夺
        this.ctrlShowRobList = obj:GetController("ShowRobList")
        if not this.robListPanel then
            ---@type UIBattleRobListPanel
            this.robListPanel = UIBattleRobListPanel.New(obj:GetChild("Com_RobList"))
            plunderHandler.sendReqPlunderInfo()
        end
        --endregion 掠夺

        this.btnRandomEvent = obj:GetChild("Btn_RandomEvent");
        this.randomCtrl = obj:GetController("Random");
        this.TextRandomEventTime = this.btnRandomEvent:GetChild("Text_Time");

        this.addEvent();
        roleId = G.serverData["roleInfo"].show.playerId
        Util.NextFrame(function()
            --mapMgr:setViewInit(1);
            Config.UIInitSucess = true;
        end)
        --if not this.uiBattleBGMap then
        --    this.uiBattleBGMap = UIBattleBGMap.New()
        --    this.uiBattleBGMap:OnCreate()
        --end

        BattleScene.init();

        lastStage = logicMgr.MapManager.getMapId();

        if this.drawWrapper == nil then
            this.drawWrapper = GoWrapper.New();
        end
        if this.drawWrapper1 == nil then
            this.drawWrapper1 = GoWrapper.New();
        end

        local icon = btn_reward:GetChild("icon");
        this.btnIcon =btn_reward:GetChild("icon");
        local effect = btn_reward:GetChild("effect");
        local icon_2 = btn_reward:GetChild("icon2")

        resMgr:LoadModelPrefab("Prefabs/UISpine/ui_offlineStage_1", function(go)
            if (spineStageEffect ~= nil) then
                destroyImmediate(spineStageEffect);
                spineStageEffect = nil
            end

            spineStageEffect = newObject(go);
            spineStageEffect:GetComponent("SkeletonGraphic").AnimationState:SetAnimation( 0,"idle", true);

            spineStageEffect:AddComponent(TCanvas);

            this.drawWrapper:SetWrapTarget(spineStageEffect, false)
            Util.Lua_SetLocalPositionXYZ(spineStageEffect.transform, 0, 0, 0)
            Util.Lua_SetLocalScaleXYZ(spineStageEffect.transform, 0.5, 0.5, 1);
            effect:SetNativeObject(this.drawWrapper);
        end)
        resMgr:LoadModelPrefab("Prefabs/UISpine/ui_offlineStage", function(go)
            if (spineStageIdel ~= nil) then
                destroyImmediate(spineStageIdel);
                spineStageIdel = nil
            end
            spineStageIdel = newObject(go);
            spineStageIdel:AddComponent(TCanvas);
            this.drawWrapper1:SetWrapTarget(spineStageIdel, false)
            Util.Lua_SetLocalPositionXYZ(spineStageIdel.transform, 0, 0, 0)
            Util.Lua_SetLocalScaleXYZ(spineStageIdel.transform, 0.5, 0.5, 1);
            icon:SetNativeObject(this.drawWrapper1)
            this.onFrameRender();
        end)
        this.RotateAnimation();
    end
    this.Refresh_ChangePlunderFunction()
    this.updateMainTask();
    this.updateTask();
    this.RefreshBossBtn()
    this.RefreshChapterRewardBtn();
    this.FriendProgress()
    this.RefreshDungeonRandomEvent();
    this.onClickNormalMode(true)
    this.onLineTime();
    this.refreshSideGirl()
    lastSyncTime = logicMgr.HeroManager.getSettleTime();

    --logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle,Config.FuncOpenType.HangupPreView,btn_dropInfo.name,btn_dropInfo);
    --logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.WorldChat, btn_chat.name, btn_chat);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.LockChat, btn_chat.name, btn_chat);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.QuickBattle, btn_quick.name, btn_quick);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.BattleRecommend, this.btnBattleRecommend.name, this.btnBattleRecommend);
    --logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.Rob, this.btn_map.name, this.btn_map);

    --logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattle, Config.FuncOpenType.Story, btn_story.name, btn_story);

    UIRedDots.addViewListen(PanelNames.UIBattle, this.quickBattleRedDotsName, btn_quick, Config.RedDotsType.FreeFastBattle);

    dungeonHandler.sendFormation();

    this.petInit()
    this.WeaknessLogic()
    --leftTransition:Play();
    --[[local battleId = Util.GetPlayerPrefs(roleId .. "joinBattle")
    if not battleId then
        battleId = 0
    end
    if logicMgr.FriendBattleManager.IsJoin() and logicMgr.FriendBattleManager.OpenChoose() then
        --if tonumber(battleId) == 0 then
        FriendBattleHandler.ReqJoinBattle(logicMgr.FriendBattleManager.GetLBSPlace())
        --end
    else
        Util.SetPlayerPrefs(roleId .. "joinBattle", 0)
    end--]]
    local mCfg = dataTable.getDataTableByStringId("t_chapter",logicMgr.MapManager.GetCurrentChapterId())
    if mCfg then
        this.ctrlMask.selectedIndex = mCfg.f_Mask
    else
        this.ctrlMask.selectedIndex = 0
    end
end

function UIBattle.updateChapterTitle()--切换普通模式
    if controllerStoryMode.selectedIndex == 1 then
        local after = logicMgr.StoryHardManager.getDungeonTableDataById() or logicMgr.StoryHardManager.getDungeonTableDataById(logicMgr.StoryHardManager.getDungeonId());
        curChapter.text = getLanguage(after.f_ChapterName);
        UIBattle.playAudio(after.f_ChapterId)
    else
        local after = logicMgr.MapManager.getNextMapcfg() or logicMgr.MapManager.getMapcfg()
        curChapter.text = getLanguage("ChapterName" .. after.f_ChapterId);
        UIBattle.playAudio(after.f_ChapterId)
    end
end
function UIBattle.onClickNormalMode(notPlay)--切换普通模式
    if not logicMgr.StoryHardManager.GetIsEntryBattle() then
        this.clearGroupBossHistory(2);
    end
    logicMgr.StoryHardManager.setIsEntryBattle(false);
    if this.uiBattleBGMap then--剧情模式地图
       this.uiBattleBGMap:OnDestroy()
       this.uiBattleBGMap = nil
    end
    if this.uiBattleBGMap1 then--剧情模式地图
        this.uiBattleBGMap1:OnDestroy()
        this.uiBattleBGMap1 = nil
    end
    BattleScene.destroyScene()
    BattleScene.loadScene(BattleScene.start);
    
    this.uiBattleBGMap = UIBattleBGMap.New()
    this.uiBattleBGMap:OnCreate()
    controllerStoryMode.selectedIndex = 0;
    this.updateChapterTitle()
    this.uiBattleBGMap:Refresh(isShowAni)
    this.RefreshBossBtn()
    UISpeed()
end

function UIBattle.onClickHardMode()--切换剧情模式
    this.clearGroupBossHistory(1);
    if  Util.GetPlayerPrefs("HardStoryRedDots") == nil then
        Util.SetPlayerPrefs("HardStoryRedDots","1")
    end   
    if this.hardModeTime then
        return
    end
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.StoryModelReward) then
        if this.uiBattleBGMap then--剧情模式地图
            this.uiBattleBGMap:OnDestroy()
            this.uiBattleBGMap = nil
        end
        if this.uiBattleBGMap1 then--剧情模式地图
            this.uiBattleBGMap1:OnDestroy()
            this.uiBattleBGMap1 = nil
        end
        AudioManager.Play(4020)
        UIHeadMenu.isNeedShowMask(true);
        this.ctrlNextChapter.selectedIndex = 0
        controllerStoryMode.selectedIndex = 1;
        this.updateChapterTitle()
        --BattleScene.loadScene(BattleScene.start, true);
        this.uiBattleBGMap1 = UIBattleBGMap1.New()
        this.uiBattleBGMap1:OnCreate()
        BattleScene.destroyScene()
        BattleScene.loadScene(BattleScene.start,true);
        resMgr:LoadModelPrefab("UIEff/UI_zhuanchang_jq", function(prefab)
            if this.effHardModeWrapper == nil then
                this.effHardModeWrapper = GoWrapper.New();
            end
            if this.effHardMode ~= nil then
                destroyImmediate(this.effHardMode);
                this.effHardMode = nil
            end
            this.effHardMode = newObject(prefab)
            this.effHardModeWrapper:SetWrapTarget(this.effHardMode,false)
            Util.Lua_SetLocalRotationXYZ(this.effHardMode.transform, 0, 0, 0);
            this.eff_zhuanchang_jq:SetNativeObject(this.effHardModeWrapper)
        end)
        this.hardModeTime = utimer.timeCall(function ()
            UIHeadMenu.isNeedShowMask();
            this.hardModeTime = nil;
            if this.effHardMode ~= nil then
                destroyImmediate(this.effHardMode);
                this.effHardMode = nil
            end
        end, 1200, 1);      
    else
        showUI(PanelNames.UIStoryInfo)
    end
    UISpeed()
end

function UIBattle.clearGroupBossHistory(modelType)
    local flag = false;
    local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory();
    for k, v in pairs(data) do
        if v.record and v.record.win == 1 then
            flag = true;
            break;
        end
    end
    if flag then
        if modelType == 1 then
            --dungeonHandler.reqQuitGroupBoss();
        else
            dungeonHandler.ReqQuitHardGroupBoss();
        end
        logicMgr.BattlePlaybackManager.SetGroupBossHistory();
    end
end

function UIBattle.onAutoHardMode(isgo)--自动切换剧情模式
    this.ctrlNextChapter.selectedIndex = 0
    if this.uiBattleBGMap then--剧情模式地图
        this.uiBattleBGMap:OnDestroy()
        this.uiBattleBGMap = nil
    end
    if this.uiBattleBGMap1 then--剧情模式地图
        this.uiBattleBGMap1:OnDestroy()
        this.uiBattleBGMap1 = nil
    end
    this.uiBattleBGMap1 = UIBattleBGMap1.New()
    this.uiBattleBGMap1:OnCreate()
    controllerStoryMode.selectedIndex = 1;
    BattleScene.destroyScene()
    BattleScene.loadScene(BattleScene.start,true);
    this.updateChapterTitle();
    this.onAutoBoss(isgo)
end

function UIBattle.onAutoBoss(isgo)--自动切换剧情模式
    this.uiBattleBGMap1:autoOpenBattle(isgo)
end


function UIBattle.FriendProgress()
    local info, info1 = logicMgr.FriendManager.FriendChapterInfo()
    if not info then
        friendCtrl.selectedIndex = 1
    elseif #info > 0 then
        friendCtrl.selectedIndex = 0
        friendInfo = info
    elseif #info1 > 0 then
        friendCtrl.selectedIndex = 0
        friendInfo = info1
    else
        friendCtrl.selectedIndex = 2
    end
    if friendCtrl.selectedIndex == 0 then
        table.sort(friendInfo, function(a, b)
            return a.stageId > b.stageId
        end)
        friendList.itemRenderer = this.FriendRender
        friendList.numItems = #friendInfo
    end
end

function UIBattle.FriendRender(index, obj)
    local config = friendInfo[index + 1]
    local name = obj:GetChild("friendName")
    local chapter = obj:GetChild("chapterName")
    local icon = obj:GetChild("headFriend"):GetChild("head"):GetChild("HeadIcon")
    local frame = obj:GetChild("headFriend"):GetChild("frame")
    name.text = config.name
    chapter.text = config.stageName
    UIComponentInterface:SetPlayerIcon(icon, config.pic, frame, config.picFrame)
end

function UIBattle.RotateAnimation()
    local mapId = logicMgr.MapManager.getMapId();
    if Util.GetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID") and (tonumber(Util.GetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID")) ~= mapId) and mapId ~= 0 then
        isShowAni = true;
    end

    if isShowAni then
        this.showCustomInfo(Util.GetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID"));
    else
        this.showCustomInfo(mapId);
    end
    if this.uiBattleBGMap then
        this.uiBattleBGMap:Refresh(isShowAni)
    end
end

function UIBattle.updateTeamPlayer()
    --[[if BattleScene.isPlay() then
        BattleScene.stop();
        if BattleScene.isShow then
            BattleScene.createPlayer();
        end
        BattleScene.start();
    end]]
end

function UIBattle.replyBattle()
    --挂机界面背景音乐
    UIBattle.playAudio()
    --[[if BattleScene.isPlay() then
        BattleScene.stop();
        if BattleScene.isShow then
            BattleScene.createPlayer();
        end
        BattleScene.start();
    else
        if BattleScene.isShow then
            BattleScene.createPlayer();
        end
        BattleScene.start();
    end]]
end

function UIBattle.addEvent()
    this.btnNormal.onClick:Add(this.onClickNormalMode)
    this.btnHard.onClick:Add(this.onClickHardMode)
    btn_boss.onClick:Add(this.onClickBoss2);
    btn_boss2.onClick:Add(this.onClickBoss2);
    btn_reward.onClick:Add(this.onClickReward);
    btn_chat.onClick:Add(this.onLongClickChat);
    btn_quick.onClick:Add(this.onClickQuick);
    --btn_dropInfo.onClick:Add(this.onClickDropInfo);
    this.btn_map.onClick:Add(this.onClickMap);
    this.btn_open_map.onClick:Add(this.onClickMap1)
    this.txt_cur_stage.onClick:Add(this.onClickMap1)
    btnDetails.onClick:Add(this.onClickDetails);
    --btn_story.onClick:Add(this.onClickStory)
    this.taskReceive.onClick:Add(this.onClickRewardTaskAward)
    this.bind.btnCloseWeakness.onClick:Add(this.OnClickCloseWeaknessInfo)
    this.bind.btnWeakness.onClick:Add(this.OnClickShowWeaknessInfo)
    this.Btn_PetBuff.onClick:Add(this.onClickPetBuff)
    this.Btn_PetBuffClose.onClick:Add(this.onClickPetBuffClose)
    this.TaskIcon.onClick:Add(this.onClickGoMainTask)
    this.taskOpen.onClick:Add(this.onClickMainTask)
    this.btnChapterReward.onClick:Add(this.onClickChapterReward)
    this.btnBattleRecommend.onClick:Add(this.onClickBattleRecommend)
    this.btnRandomEvent.onClick:Add(this.onClickRandomEvent)
    UIRedDots.addViewListen(PanelNames.UIBattle, this.quickBattleRedDotsName, btn_quick, Config.RedDotsType.FreeFastBattle);
    --UIRedDots.addViewListen(PanelNames.UIBattle, "btn_story", btn_story, Config.RedDotsType.Story)
    UIRedDots.addViewListen(PanelNames.UIBattle, "btn_chat", btn_chat, Config.RedDotsType.Chat)

    UIRedDots.addViewListen(PanelNames.UIBattle, "btn_map", this.btn_map, Config.RedDotsType.WorldMap) -- 世界地图红点
    UIRedDots.addViewListen(PanelNames.UIBattle, "UIBattle"..this.btnBattleRecommend.gameObjectName, this.btnBattleRecommend, Config.RedDotsType.BattleRecommend);
    UIRedDots.addViewListen(PanelNames.UIBattle,"UIBattle"..this.btnHard.gameObjectName, this.btnHard, Config.RedDotsType.HardStory);
    UIRedDots.addViewListen(PanelNames.UIBattle,"UIBattle"..this.btn_boss2.gameObjectName, this.btn_boss2, Config.RedDotsType.HardStory);

    ListenEvent(Config.EventType.RefreshSideGirlSpine, this.refreshSideGirl)
end

function UIBattle.removeEvent()
    btn_boss.onClick:Remove(this.onClickBoss2);
    btn_boss2.onClick:Remove(this.onClickBoss2);
    btn_reward.onClick:Remove(this.onClickReward);
    btn_chat.onClick:Remove(this.onLongClickChat);
    --btn_func.onClick:Remove(this.onClickFunc);
    btn_quick.onClick:Remove(this.onClickQuick);
    --btn_dropInfo.onClick:Remove(this.onClickDropInfo);
    btn_map.onClick:Remove(this.onClickMap);
    this.btn_open_map.onClick:Clear()
    this.txt_cur_stage.onClick:Clear()
    btnDetails.onClick:Remove(this.onClickDetails);
    this.taskReceive.onClick:Remove(this.onClickRewardTaskAward);
    this.bind.btnWeakness.onClick:Remove(this.OnClickShowWeaknessInfo)
    this.bind.btnCloseWeakness.onClick:Remove(this.OnClickCloseWeaknessInfo)
    this.Btn_PetBuff.onClick:Remove(this.onClickPetBuff)
    this.Btn_PetBuffClose.onClick:Remove(this.onClickPetBuffClose)
    this.TaskIcon.onClick:Remove(this.onClickGoMainTask)
    this.taskOpen.onClick:Remove(this.onClickMainTask)
    this.btnChapterReward.onClick:Remove(this.onClickChapterReward)
    this.btnBattleRecommend.onClick:Remove(this.onClickBattleRecommend)
    this.btnRandomEvent.onClick:Remove(this.onClickRandomEvent)
    UIRedDots.removeViewEvent(PanelNames.UIBattle);
    CloseEvent(Config.EventType.RefreshSideGirlSpine, this.refreshSideGirl)
end

function UIBattle.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_BattleFormation, this.updateTeamPlayer);
    ListenEvent(Config.EventType.Fight_Update_TeamPlayer, this.updateTeamPlayer);
    ListenEvent(Config.EventType.Fight_Update_TowerInfo, this.updateTowerInfo);
    ListenEvent(Config.EventType.Fight_Show_Shadow, this.showShadow);
    ListenEvent(Config.EventType.Fight_Hide_Shadow, this.hideShadow);
    ListenEvent(Config.EventType.SettleReward, this.openSettlePanel);
    ListenEvent(Config.EventType.Drop_GoldAndExp, this.DropGoldAndExp);
    ListenEvent(Config.EventType.Fight_Enter, this.closeAllUI);
    ListenEvent(Config.EventType.StageRotate, this.RotateAnimation)
    ListenEvent(Config.EventType.Res_TaskInfo_Get, this.updateTask)
    ListenEvent(Config.EventType.Res_TaskInfo_Get, this.updateMainTask)
    ListenEvent(Config.EventType.Fresh_NewStage, this.updateTask)
    ListenEvent(Config.EventType.JoinBattle, this.JoinBattleTips)
    ListenEvent(Config.EventType.Fresh_MyFriends, this.FriendProgress);
    ListenEvent(Config.EventType.BattleBGMapFadeIn, this.BattleBGMapFadeIn)
    ListenEvent(Config.EventType.Fresh_TaskInfo_ALL, this.TaskAllUpdate);
    ListenEvent(Config.EventType.UIBattleChapterRewardSuc, this.UIBattleChapterRewardSuc);
    ListenEvent(Config.EventType.Fresh_WorldMapRevengeList,this.onFrameRender)
    ListenEvent(Config.EventType.Reconnect,this.DoReconnect)
    ListenEvent(Config.EventType.UILayerMaskChanged,this.UILayerMaskChanged)
    ListenEvent(Config.EventType.Refresh_ChangePlunderFunction,this.Refresh_ChangePlunderFunction)
    ListenEvent(Config.EventType.Refresh_PlunderInfo,this.Refresh_PlunderInfo)
    ListenEvent(Config.EventType.Refresh_OpenPlunder,this.Refresh_OpenPlunder)
    ListenEvent(Config.EventType.Fresh_DungeonRandomEventAccept,this.RefreshDungeonRandomEvent)
    ListenEvent(Config.EventType.WaitingBattleFinishedPopUp,this.WaitingBattleFinishedPopUpMsg)

end

function UIBattle.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_BattleFormation, this.updateTeamPlayer);
    CloseEvent(Config.EventType.Fight_Update_TeamPlayer, this.updateTeamPlayer);
    CloseEvent(Config.EventType.Fight_Update_TowerInfo, this.updateTowerInfo);
    CloseEvent(Config.EventType.Fight_Show_Shadow, this.showShadow);
    CloseEvent(Config.EventType.Fight_Hide_Shadow, this.hideShadow);
    CloseEvent(Config.EventType.SettleReward, this.openSettlePanel);
    CloseEvent(Config.EventType.Fresh_TaskInfo_ALL, this.TaskAllUpdate);
    CloseEvent(Config.EventType.Drop_GoldAndExp, this.DropGoldAndExp);
    CloseEvent(Config.EventType.Fight_Enter, this.closeAllUI);
    CloseEvent(Config.EventType.StageRotate, this.RotateAnimation)
    CloseEvent(Config.EventType.Res_TaskInfo_Get, this.updateTask)
    CloseEvent(Config.EventType.Res_TaskInfo_Get, this.updateMainTask)
    CloseEvent(Config.EventType.Fresh_NewStage, this.updateTask)
    CloseEvent(Config.EventType.JoinBattle, this.JoinBattleTips)
    CloseEvent(Config.EventType.Fresh_MyFriends, this.FriendProgress);
    CloseEvent(Config.EventType.BattleBGMapFadeIn, this.BattleBGMapFadeIn)
    CloseEvent(Config.EventType.UIBattleChapterRewardSuc, this.UIBattleChapterRewardSuc);
    CloseEvent(Config.EventType.Fresh_WorldMapRevengeList,this.onFrameRender())
    CloseEvent(Config.EventType.Reconnect,this.DoReconnect)
    CloseEvent(Config.EventType.UILayerMaskChanged,this.UILayerMaskChanged)
    CloseEvent(Config.EventType.Refresh_ChangePlunderFunction,this.Refresh_ChangePlunderFunction)
    CloseEvent(Config.EventType.Refresh_PlunderInfo,this.Refresh_PlunderInfo)
    CloseEvent(Config.EventType.Refresh_OpenPlunder,this.Refresh_OpenPlunder)
    CloseEvent(Config.EventType.Fresh_DungeonRandomEventAccept,this.RefreshDungeonRandomEvent)
    CloseEvent(Config.EventType.WaitingBattleFinishedPopUp,this.WaitingBattleFinishedPopUpMsg)
    tableTaskInfo = nil;

    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIBattle);

end

function UIBattle.JoinBattleTips()
    --local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
    --pop.Init("35");
    Util.SetPlayerPrefs(roleId .. "joinBattle", 1)
    Util.SetPlayerPrefs(roleId .. "friendBattleGroup", logicMgr.FriendBattleManager.GetLBSPlace())
end

function UIBattle.OnDestroy()
    if (spineStageEffect ~= nil) then
        destroy(spineStageEffect);
    end
    if (spineStageIdel ~= nil) then
        destroy(spineStageIdel);
    end
    if (spineDrop ~= nil) then
        destroy(spineDrop);
    end
    if this.effHardMode ~= nil then
        destroyImmediate(this.effHardMode);
        this.effHardMode = nil
    end
    if this.hardModeTime ~= nil then
        utimer.remove(this.hardModeTime)
        this.hardModeTime = nil
    end
    if posuiObj then
        posuiObj = nil
    end
    if this.drawWrapper then
        this.drawWrapper:Dispose()
        this.drawWrapper = nil
    end
    if this.drawWrapper1 then
        this.drawWrapper1:Dispose()
        this.drawWrapper1 = nil
    end

    if posuiWrap then
        posuiWrap:Dispose()
        posuiWrap = nil
    end
    for key, value in pairs(dropWrap) do
        if not HelperFunc.IsNull(value) then
            value:Dispose();
        end
    end
    dropWrap = {}
    for key, value in pairs(listParticle) do
        destroy(value)
    end
    listParticle = {}

    this.removeRandomEventTimer();
    if onlineTimer then
        utimer.remove(onlineTimer)
        onlineTimer = nil
    end
    this.DestoryWeaknessTimer()
    spine = nil;
    this.removeEvent();
    this.InitLocalData()
    if dropTimer1 then
        utimer.remove(dropTimer1)
    end
    if dropTimer2 then
        utimer.remove(dropTimer2)
    end
    --[[if this.carPanel then
        this.carPanel:OnDestroy()
    end
    this.carPanel = nil]]
    if this.uiBattleBGMap then
        this.uiBattleBGMap:OnDestroy()
        this.uiBattleBGMap = nil
    end
    if this.uiBattleBGMap1 then
        this.uiBattleBGMap1:OnDestroy()
        this.uiBattleBGMap1 = nil
    end
    if this.robListPanel then
        this.robListPanel:Destroy()
        this.robListPanel = nil
    end
end

function UIBattle.OnEnable()

    AudioManager.SetSwitch("Battle_SwitchGroup", "Battle_ADV_Switch")
    if battleMainRoot ~= nil then
        battleMainRoot.gameObject:SetActive(true);
    end
    delayDisableCamera = false
    this.LocalListenEvent();
    FireEvent(Config.EventType.Show_HeadMenu_HeadIcon, true);
    FireEvent(Config.EventType.Fresh_WorldMap)
    if this.uiBattleBGMap then
        this.uiBattleBGMap:OnEnable()
    end
   
   if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.StoryModel) then
        controllerStoryModeOpen.selectedIndex = 1
        this.initReward()
    else
       controllerStoryModeOpen.selectedIndex = 0
    end
end

function UIBattle.initReward()
    mainReward:RemoveChildrenToPool()
    local data =decodeJsonStrToTabel(G.dataTable["t_functionswitch"][tostring(Config.FuncOpenType.StoryModelReward)].f_FunctionRroduction) 
    for i = 1, table.nums(data) do
        local item = mainReward:AddItemFromPool()
        logicMgr.CostManager.RefreshItem(item,{data[i]});
    end
end
--- 禁用战斗场景摄像机
--- @private
function UIBattle.DisableCamera()
    if not delayDisableCamera then
        return
    end

    delayDisableCamera = false

    if not HelperFunc.IsNull(battleMainRoot) then
        battleMainRoot.gameObject:SetActive(false);
    end
end

function UIBattle.OnDisable()
    delayDisableCamera = true
    -- 下一帧禁用
    utimer.delayCall(this.DisableCamera, 0)
    this.LocalCloseEvent();
    UIBattle.stopAudio()
    --FireEvent(Config.EventType.Show_HeadMenu_HeadIcon,false);
    this.removeRandomEventTimer();
    if onlineTimer then
        utimer.remove(onlineTimer)
        onlineTimer = nil
    end
    --if hasInit then
    --    BattleScene.stop();
    --end
    if isShowAni then
        isShowAni = false
    end
    if dropTimer1 then
        utimer.remove(dropTimer1)
    end
    if dropTimer2 then
        utimer.remove(dropTimer2)
    end
    if this.uiBattleBGMap then
        this.uiBattleBGMap:OnDisable()
    end
end
function UIBattle.RefreshBossBtn()
    if not this.ctrlNextChapter or controllerStoryMode.selectedIndex == 1 then return end
    local hasPre = logicMgr.MapManager.HasChapterRewardByPre()
    if hasPre then
        this.hasChapterReward = true
        this.ctrlNextChapter.selectedIndex = 1
        return
    end
    local isEndLevel = logicMgr.MapManager.IsEndChapterMapId(MapManager.getMapId())
    local hasReward, rewardGet = logicMgr.MapManager.GetChapterReward(MapManager.getMapId())
    this.hasChapterReward = isEndLevel and hasReward and not rewardGet
    this.ctrlNextChapter.selectedIndex = 0
    if isEndLevel then
        if hasReward and not rewardGet then
            --当前章节奖励未领取
            this.ctrlNextChapter.selectedIndex = 1
        end
    end
end
function UIBattle.RefreshChapterRewardBtn()
    local itemModelId;
    local isEndLevel = logicMgr.MapManager.IsEndChapterMapId(MapManager.getMapId());
    local curChapter = logicMgr.MapManager.GetCurrentChapterId();
    local taskCfg;
    if isEndLevel then
        local hasReward, rewardGet = logicMgr.MapManager.GetChapterReward(MapManager.getMapId());
        local nextChapterTaskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter + 1);
        if (hasReward and not rewardGet) or (nextChapterTaskCfg == nil) then
            --当前章节奖励未领取
            taskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter);
            this.btnChapterRewardTips.text = "";
        else
            --显示下一章节奖励
            taskCfg = nextChapterTaskCfg;
            local maxMapCfg = MapManager.GetChapterMaxStageNum(curChapter + 1);
            this.btnChapterRewardTips.text = string.format(getLanguage("ChapterRewardText3"), maxMapCfg.f_StageNum);
        end
    else
        taskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter);
        local curMapCfg = logicMgr.MapManager.getMapcfg();
        local maxMapCfg = MapManager.GetChapterMaxStageNum(curChapter);
        this.btnChapterRewardTips.text = string.format(getLanguage("ChapterRewardText3"), maxMapCfg.f_StageNum - curMapCfg.f_StageNum);
    end
    if taskCfg ~= nil and taskCfg.f_Award ~= nil and taskCfg.f_Award ~= "" then
        local reward = decodeJsonStrToTabel(taskCfg.f_Award)[1];
        if reward ~= nil then
            itemModelId = reward[1];
        end
    end
    if itemModelId ~= nil then
        UIComponentInterface:SetItemAllById(this.btnChapterRewardIcon, nil, nil, itemModelId);
    else
        this.btnChapterRewardIcon.url = "";
    end
end
function UIBattle.BattleBGMapFadeIn(onlyChangeText)
    if onlyChangeText then
        this.ctrlNextChapter.selectedIndex = 0
    else
        this.RefreshBossBtn()
    end
    this.RefreshChapterRewardBtn();
end

-- 多队的话会有关卡详情弹出(完整流程),如果直接挑战用UIBattle.onClickBoss()
function UIBattle.onClickBoss2()
    --logicMgr.BattlePlaybackManager.playReport(101,EnumConst.FightTypeConst.PerformBattle)
    if controllerStoryMode.selectedIndex == 0 then
        local hasPre = logicMgr.MapManager.HasChapterRewardByPre()
        local isEndLevel = logicMgr.MapManager.IsEndChapterMapId(MapManager.getMapId())
        local hasReward, rewardGet = logicMgr.MapManager.GetChapterReward(MapManager.getMapId())
        if hasPre or isEndLevel and hasReward and not rewardGet then
            --有章节奖励要领
            if this.uiBattleBGMap:IsTransition() then
                return
            end
            this.uiBattleBGMap:ClickGetChapterReward()
            return
        end
        if logicMgr.MapManager.getStageNeedTeamNum() < 0 then
            UISysTips.AddMsg(getLanguage("ErrorCode_5000"));
        elseif logicMgr.MapManager.getStageNeedTeamNum() > 1 then
            showUI(PanelNames.UITeamsDetails, this.onClickBoss);
        else
            this.onClickBoss();
        end
    else
        this.uiBattleBGMap1:openBattle()
    end
end

function UIBattle.onClickBoss()
    if this.isWaitingBattleFinishedPopUp then
        logError("waiting BattleFinishedPopUp done")
        return
    end
    local hasPre = logicMgr.MapManager.HasChapterRewardByPre()
    local isEndLevel = logicMgr.MapManager.IsEndChapterMapId(MapManager.getMapId())
    local hasReward, rewardGet = logicMgr.MapManager.GetChapterReward(MapManager.getMapId())
    if hasPre or isEndLevel and hasReward and not rewardGet then
        --有章节奖励要领
        if this.uiBattleBGMap:IsTransition() then
            return
        end
        this.uiBattleBGMap:ClickGetChapterReward()
        return
    end
    Util.SetOrderType(btn_boss.displayObject.gameObject,"Default");
    --dungeonHandler.sendFormation();
    --BattleScene.stop();
    TAManager.TrackByDictionary("challenge_stage", { next_stage_id = logicMgr.MapManager.getNextStage() })

    showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.DUNGEON, nil, function(formations, _, Info, index)
        local curStage = logicMgr.MapManager.getNextStage();
        if curStage > 0 then
            --CloseEvent(Config.EventType.Fresh_TaskInfo, this.collectTaskInfo);
            --ListenEvent(Config.EventType.Fresh_TaskInfo, this.collectTaskInfo);
            UIWaiting.WaitingShow(true);
            tableTaskInfo = nil;
            battleInfo = Info;
            log("curStage " .. curStage)
            if logicMgr.MapManager.getStageNeedTeamNum(curStage) > 1 then
                dungeonHandler.sendGroupBossMessage(curStage, formations, Info, index);
            else
                dungeonHandler.sendBossMessage(curStage, formations[1], Info);
            end
            dungeonHandler.sendFormation();
            logicMgr.DungeonRandomEventManager.updateLeaseHero(formations);
            --this.closeAllUI();
        end
    end, this.replyBattle);
end

function UIBattle.closeAllUI()
    closeUI(PanelNames.UIBottom);
    closeUI(PanelResNames.UIHeadMenu);
    closeUI(PanelNames.UIBattle);
    closeUI(PanelNames.UIFuncMenu);
    closeUI(PanelNames.UIBattleTeam);

    --BattleScene.stop();
end

--[[function UIBattle.onClickBoss1()
    --BattleScene.stop();
    if FightManager.hasInit then
        FightManager.stopCommand();
        FightManager.destroy();
    end

    local fightreport = UIBattle.fightReports();--v.data.fight;
    FightManager.init();
    FightManager.readReport(fightreport, EnumConst.FightTypeConst.DUNGEON, 1);
    BattlePlaybackManager.setBattleResult(1);
    UIBattle.gotoFight();

    return ;
end]]

function UIBattle.DropGoldAndExp(msg)
    --[[if not hasInit then
        return
    end--]]
	battleMainRoot=battleMainRoot or panelMgr.BattleMain
	if not  battleMainRoot then
		logMy("battleMainRoot is null")
		return
	end
    local camera = battleMainRoot.transform:Find("CameraMain"):GetComponent("Camera")
    local pos = Util.WorldToScreenPoint(camera, msg.position);
    local tpos = Vector2.New()
    tpos:Set(pos.x + Screen.width * 0.5, Screen.height * 0.5 - pos.y)
    local pt = FairyGUI.GRoot.inst:GlobalToLocal(tpos);
    index = 3 - index;
    listPool[index].visible = true;
    listPool[index]:SetXY(pt.x + 80, pt.y + 80);

    resMgr:LoadModelPrefab("Fx/EFF_drop", function(go)
        if (dropWrap[index] == nil) then
            dropWrap[index] = GoWrapper.New()
        end   
        if (listParticle[index] ~= nil) then
            destroyImmediate(listParticle[index]);
            listParticle[index] = nil
        end
        listParticle[index] = newObject(go);
        listParticle[index].name = "EFF_drop";
        listParticle[index]:AddComponent(TCanvas);
        dropWrap[index]:SetWrapTarget(listParticle[index], false)
        listPool[index]:SetNativeObject(dropWrap[index])
        Util.Lua_SetLocalPositionXYZ(listParticle[index].transform, 0, 0, 0);
        local move = listPool[index]:TweenMove(pt.x, pt.y, 1);
        move:SetEase(EaseType.CubicOut);
    end);
    if dropTimer1 then
        utimer.remove(dropTimer1)
    end
    dropTimer1 = utimer.timeCall(function()
        local x = btn_reward.x + btn_reward.width / 2
        local y = btn_reward.y + btn_reward.height / 2
        local move = listPool[index]:TweenMove(x, y, 0.5);
        move:SetEase(EaseType.QuintOut);
        local move2 = listPool[3 - index]:TweenMove(x, y, 0.5);
        move2:SetEase(EaseType.QuintOut);
    end, 800, 1)
    if dropTimer2 then
        utimer.remove(dropTimer2)
    end
end

function UIBattle.onClickReward()
    if Config.serverTime / 1000 - lastSyncTime >= G.dataTable["t_global"]["94"]["f_int_value"] then
        --Util.AddAction(spineStageEffect, "idle", true, 0.5);
        -- TAManager.TrackByDictionary("stage_click_reward")
        playerHandler.sendSettleMessage();
    else
        showUI(PanelNames.UIOfflineRewards, { seconds = Config.serverTime / 1000 - lastSyncTime, items = {} });
    end
end

function UIBattle.onLongClickChat()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.LockChat, true, btn_chat) then
        showUI(PanelNames.UIChatPanel);
    end
end

function UIBattle.update()
    if Input.GetMouseButton(0) then
        local mouseXPos = Input.mousePosition.x;
        local mouseYPos = Input.mousePosition.y;
        Xoffset = mouseXPos - curMouseXPos;
        Yoffset = mouseYPos - curMouseYPos;

        local limitX = Mathf.Clamp(chatPosX + Xoffset, -500, 500);
        local limitY = Mathf.Clamp(chatPosY + Yoffset, -800, 800);
        Util.Lua_SetLocalPositionXYZ(btn_chat.displayObject.gameObject, limitX, limitY, 0);
    end

    if Input.GetMouseButtonUp(0) then
        local x, y = Util.Lua_GetLocalPositionXYZ(btn_chat.displayObject.gameObject, 0, 0, 0)
        Util.SetPlayerPrefs("saveChatBtnPosX", x);
        Util.SetPlayerPrefs("saveChatBtnPosY", y);

        if Xoffset == 0 and Yoffset == 0 then
            showUI(PanelNames.UIChatPanel);
        end

        UpdateBeat:Remove(this.update, this);
    end
end

function UIBattle.onClickFunc()
    showUI(PanelNames.UIFuncMenu);
    this.onCloseFunc();
    UICity.onCloseFunc();
end

function UIBattle.onCloseFunc()
    if transform ~= nil then
        transform:Find("FuncBtn"):GetComponent("Animation"):Play("LeftTop");
    end
end

function UIBattle.onOpenFunc()
    if transform ~= nil then
        transform:Find("FuncBtn"):GetComponent("Animation"):Play("LeftTop_1");
    end
end

--function UIBattle.onClickDropInfo()
--    showUI(PanelNames.UIDropInfo);
--end

function UIBattle.onClickQuick()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.QuickBattle) then
        showUI(PanelNames.UIQuickBattleTips);--快速战斗
    end
end

function UIBattle.onClickDetails()
    showUI(PanelNames.UIDuplicationDetails);
end
--function UIBattle.onClickStory()
--    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Story, true,btn_story) then
--        return
--    end
--    showUI(PanelNames.UIStoryReview)
--end
function UIBattle.onClickMap()
    if FuncOpenManager.isOpen(Config.FuncOpenType.Rob, true, this.btn_map)then
        if plunderHandler.change_plunder_function_type == 1 then
            this.Refresh_OpenPlunder(true)
        else
            showUI(PanelNames.UIOpenPopup, 0)
        end
    end

end

function UIBattle.onClickMap1()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BigMap, true, btn_map) then
        showUI(PanelNames.UIBigMap, plunderHandler.have_search, true);
    end
end

function UIBattle.initMapInfo(mapdata)
    if not hasInit then
        return ;
    end
    this.changeMapResult(mapdata);
    this.stop = false;
end

--显示挂机收益
function UIBattle.showIdleNotice()
    if G.serverData["roleInfo"] ~= nil then
        local mapcfg = this.stageConfig[tostring(logicMgr.MapManager.getMapId())];
        lab_exp.text = mapcfg.f_Exp .. "/m";
        lab_money.text = mapcfg.f_Coin .. "/m";
    end
end

function UIBattle.showCustomInfo()
    --aniLevel:Stop();

    local mapId = nil;
    if isShowAni then
        mapId = Util.GetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID");
        Util.SetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID", logicMgr.MapManager.getMapId());
    else
        mapId = logicMgr.MapManager.getMapId();
        if mapId ~= 0 then
            Util.SetPlayerPrefs(roleId .. AppConst.ServerId .. "mapID", mapId);
        end
    end
    local current = this.stageConfig[tostring(mapId)];
    if current.f_NextStage ~= nil and current.f_NextStage > 0 then
        current = this.stageConfig[tostring(current.f_NextStage)];
        mapId = current.f_StageId;
    end
    --[[
    if current ~= nil then
        
        if isShowAni then
            txtCurLevel.text = string.TextColor((current.f_ChapterId .. "-" .. current.f_StageNum), "#C8C2B8")
        else
            txtCurLevel.text = current.f_ChapterId .. "-" .. current.f_StageNum;
        end
        this.iconCurLevel:GetController("iconType").selectedIndex = current.f_type;
        local after = this.stageConfig[tostring(current.f_NextStage)];
        if after ~= nil then
            txtAfterLevel.visible = true;
            if isShowAni then
                txtAfterLevel.text = string.TextColor((after.f_ChapterId .. "-" .. after.f_StageNum), "#DEBD49");
            else
                txtAfterLevel.text = after.f_ChapterId .. "-" .. after.f_StageNum;
            end
            this.iconAfterLevel.visible = true;
            this.iconAfterLevel:GetController("iconType").selectedIndex = after.f_type;
            local afterafter = nil
            if after then
                afterafter = this.stageConfig[tostring(after.f_NextStage)];
            end
            if afterafter ~= nil then
                txtAfterAfterLevel.visible = true;
                txtAfterAfterLevel.text = afterafter.f_ChapterId .. "-" .. afterafter.f_StageNum;
                this.iconAfterAfterLevel.visible = true;
                this.iconAfterAfterLevel:GetController("iconType").selectedIndex = afterafter.f_type;
            else
                this.iconAfterAfterLevel.visible = false;
                txtAfterAfterLevel.visible = false;
            end
            local after_level = nil
            if afterafter then
                after_level = this.stageConfig[tostring(afterafter.f_NextStage)]
            end
            if after_level ~= nil then
                txtAfter_level.text = after_level.f_ChapterId .. "-" .. after_level.f_StageNum;
                this.iconAfter_level.visible = true;
                this.iconAfter_level:GetController("iconType").selectedIndex = after_level.f_type;
            else
                this.iconAfter_level.visible = false;
                txtAfter_level.visible = false;
            end
        else
            this.iconAfterLevel.visible = false;
            txtAfterLevel.visible = false;
        end

        local before = nil;
        for key, value in pairs(this.stageConfig) do
            if value.f_NextStage == mapId then
                before = value;
                break ;
            end
        end
        if before ~= nil then
            txtBeforeLevel.visible = true;
            if before.f_StageNum == 0 then
                txtBeforeLevel.text = "";
            else
                txtBeforeLevel.text = before.f_ChapterId .. "-" .. before.f_StageNum;
                --this.iconBeforeLevel.visible = true;
                --this.iconBeforeLevel:GetController("iconType").selectedIndex = before.f_type;
            end
            local beforeBefore = nil;
            for key, value in pairs(this.stageConfig) do
                if value.f_NextStage == before.f_StageId and value.f_StageId ~= 0 then
                    beforeBefore = value;
                    break ;
                end
            end
            if beforeBefore ~= nil then
                if beforeBefore.f_ChapterId == 70 and beforeBefore.f_StageNum == 60 then
                    txtBeforeBeforeLevel.text = "";
                else
                    txtBeforeBeforeLevel.visible = true;
                    txtBeforeBeforeLevel.text = beforeBefore.f_ChapterId .. "-" .. beforeBefore.f_StageNum;
                    --this.iconBeforeBeforeLevel.visible = true;
                    --this.iconBeforeBeforeLevel:GetController("iconType").selectedIndex = beforeBefore.f_type;
                end
            else
                txtBeforeBeforeLevel.visible = false;
            end
        else
            txtBeforeLevel.visible = false;
            txtBeforeBeforeLevel.visible = false;
        end
        this.iconBeforeLevel.visible = false;
        this.iconBeforeBeforeLevel.visible = false;
    end
    
        ]]
    if isShowAni then
        leftTransition:Play()
        AudioManager.Play(AudioManager.ani_compass_swing)   --关卡轮盘旋转音效
        --this.iconCurLevel.visible = false
    end
end

--刷新挂机收益按钮图标
function UIBattle.onLineTime()
    if onlineTimer then
        utimer.remove(onlineTimer)
        onlineTimer = nil
    end
    onlineTimer = utimer.timeCall(function()
        this.onFrameRender();
    end, 1000, -1)
end

function UIBattle.onFrameRender()
    if not plunderHandler.GetRevengeListRedDotData() then
        if (posuiObj ~= nil) then
            destroyImmediate(posuiObj);
            posuiObj = nil
        end
        if spineStageIdel ~= nil then
            spineStageIdel:GetComponent("SkeletonGraphic").AnimationState:SetAnimation( 0,"sj7", true);
        end
        this.collectTipsController.selectedIndex = 0;
        local onlineTime = (Config.serverTime / 1000 - logicMgr.HeroManager.getSettleTime()) / 60;
        if onlineTime * 75 >= logicMgr.HeroManager.getSettleingMaxTime() then -- 挂机时间大于最大时长的80%
            this.collectTipsController.selectedIndex = 1;
            this.collectTipsText.text = getLanguage("UIBattleCollectionTips1");
        end
        if onlineTime * 60 >= logicMgr.HeroManager.getSettleingMaxTime() then -- 挂机时间满了
            this.collectTipsController.selectedIndex = 1;
            this.collectTipsText.text = getLanguage("UIBattleCollectionTips2");
        end
        local index = 1;
        if this.aniStageConfig then
            for i = 1, #this.aniStageConfig do
                if onlineTime >= this.aniStageConfig[i] then
                    index = i;
                else
                    break ;
                end
            end
        end
        if this.curAniIndex then
            if this.curAniIndex ~= index then
                this.curAniIndex = index;
                if index > 9 then
                    index = 9
                end
                if index == 1 then
                    if not HelperFunc.IsNull(this.spineEffectBox) then
                        this.spineEffectBox.skinName = "default"
                    end
                else
                    if not HelperFunc.IsNull(this.spineEffectBox) then
                        this.spineEffectBox.skinName = tostring(index - 1)
                    end
                end

            end
        end
    else
        Util.AddAction(spineStageIdel, "idle", true);
    end
end

--- TODO: move to BattlePlaybackManager
function UIBattle.gotoFight(finishCall)
    if shadow ~= nil then
    end

    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem)
    ctrlItem.CacheHeros()
    BattleScene.pause();
    BattleScene.destroyScene();
    tableTaskInfo = nil;
    showUI(PanelNames.UILoadingBattle, FightManager.resList, function()
        DestoryUI(PanelNames.UILoadingBattle);
        hideOtherUI(true);
        showUI(PanelNames.UIBattleMain, nil, battleInfo);
        FightManager.entrance()
        if finishCall then
            finishCall()
        end
    end);
end

--切换地图收到消息后，1.5秒屏幕暗下去，然后暂停0.5秒，1秒后在淡出
function UIBattle.changeMapResult(d)
    if d.first == 1 or d.mapChange == 0 then
        return ;
    end
    local t = shadow.material:DOFade(2, 2.5);
    t:OnStepComplete(this.hideComplete);
    collectgarbage("collect");
end

function UIBattle.hideComplete()
    if shadow == nil then
        return ;
    end
    local t = shadow.material:DOFade(0, 1);
    t:OnStepComplete(this.complete);
end

function UIBattle.complete()

end

function UIBattle.updateTowerInfo()
    --BattleScene.stop();
end

function UIBattle.openSettlePanel(data)
    this.onLineTime();
    lastSyncTime = logicMgr.HeroManager.getSettleTime();
    local datas = {};
    for i = 1, #data.items do
        local modelId = data.items[i].itemModelId;
        local itemData = nil;
        if logicMgr.ItemManager.IsEquip(modelId) then
            local singleConfig = this.equipConfig[tostring(modelId)];
            if singleConfig ~= nil then
                itemData = {
                    itemModelId = singleConfig.f_EquipId,
                    num = data.items[i].num,
                    quality = singleConfig.f_EquipQuality,
                    icon = singleConfig.f_EquipIcon,
                    level = singleConfig.f_EquipLv,
                    name = getLanguage(singleConfig.f_ItemName)
                };
                table.insert(datas, itemData);
            end
        else
            local singleConfig = this.itemConfig[tostring(modelId)];
            if singleConfig ~= nil then
                itemData = {
                    itemModelId = singleConfig.f_itemModelId,
                    num = data.items[i].num,
                    quality = singleConfig.f_Quality,
                    icon = singleConfig.f_Icon,
                    name = getLanguage(singleConfig.f_ItemName)
                };
            end
            table.insert(datas, itemData);
        end

    end
    showUI(PanelNames.UIOfflineRewards, { seconds = data.time, items = datas, plunders = data.plunders });
end

function UIBattle.TaskAllUpdate()
    this.RefreshBossBtn()
end

function UIBattle.showShadow()
    if shadow ~= nil then
        shadow.visible = true;
        shadowShowAni:Play(this.complete_Show)
    end
end

function UIBattle.hideShadow()
    if shadow ~= nil then
        shadow.visible = true;
        shadowHideAni:Play(this.complete_Hide);
    end
end

function UIBattle.complete_Show()
    --BattleScene.changeState(EnumConst.BattleSceneStateEnum.NONE);
    this.hideShadow();
end

function UIBattle.complete_Hide()
    showUI(PanelNames.UIHeadMenu, true);
    showUI(PanelNames.UIBattle);
    --BattleScene.start();
end

function UIBattle.fightReports()
    local fightreport = '';
    return fightreport;
end

--- 关卡削弱处理
function UIBattle.WeaknessLogic()
    local passTime = logicMgr.FubenModel.GetPassTimeForLast()

    this.bind.ctrlWeakness.selectedIndex = 0
    if passTime ~= 0 then
        this.DestoryWeaknessTimer()
        this.timer = utimer.timeCall(function(...)
            local waitTime = HelperFunc.GetServerTime() - passTime

            this.bind.ctrlWeakness.selectedIndex = 0
            if waitTime > 86400 then
                this.bind.ctrlWeakness.selectedIndex = 1

            end
        end, 1000, -1)
    end
end

function UIBattle.DestoryWeaknessTimer()
    if this.timer then
        utimer.remove(this.timer)
        this.timer = nil
    end
end

function UIBattle.OnClickCloseWeaknessInfo()
    this.bind.ctrlContent.selectedIndex = 0
end

function UIBattle.OnClickShowWeaknessInfo()
    local passTime = logicMgr.FubenModel.GetPassTimeForLast()
    local waitTime = HelperFunc.GetServerTime() - passTime
    local day = math.floor(waitTime / 86400)
    if day > 0 then
        local str1 = string.format(getLanguage("Sys_StageMonsterNerfTip1"), tostring(day))
        this.bind.txtContent1.text = str1

        local isMax = logicMgr.FubenModel.CheckIsMaxLevel(day)
        this.bind.txtContent2.visible = not isMax
        if not isMax then
            local nexLev = day + 1
            local tarTime = passTime + nexLev * 86400
            local time = tarTime - HelperFunc.GetServerTime()
            local str2 = string.format(getLanguage("Sys_StageMonsterNerfTip2"), HelperFunc.GetSurpTimeStr(time))
            this.bind.txtContent2.text = str2
        end
    end
end

function UIBattle.updateTask(id)
    if id and id ~= this.nowTaskId then
        return ;
    end
    local taskConfig = logicMgr.TaskManager.getRemarkShowDataByType(EnumConst.AchieveTaskType.Custom);
    this.nextController.selectedIndex = 0;
    this.nowTaskId = nil;
    this.nowTaskStatus = nil;
    if #taskConfig > 0 then
        table.sort(taskConfig, function(a, b)
            return a.f_TaskId < b.f_TaskId
        end);
        local taskTable = taskConfig[1];
        local taskData = logicMgr.TaskManager.getTaskServerData(taskTable.f_TaskId);
        if taskData.status == 1 then
            this.nextController.selectedIndex = 2;
            this.TaskTitle.text = getLanguage("ChapterRewardTips4");
        elseif taskData.status == 0 then
            this.nextController.selectedIndex = 1;
            local curTable = logicMgr.MapManager.GetMapcfgByID(taskTable.f_Progress);
            local nowMapTable = logicMgr.MapManager.getMapcfg();
            if curTable ~= nil and nowMapTable ~= nil then
                local num = curTable.f_StageNum - nowMapTable.f_StageNum;
                local nowChapterId = nowMapTable.f_ChapterId;
                while(nowChapterId < curTable.f_ChapterId) do
                    num = logicMgr.MapManager.getMapStageNumByChapter(nowChapterId) + num;
                    nowChapterId = nowChapterId + 1;
                end
                this.TaskTitle.text = string.format(getLanguage("ChapterRewardTips3"), num)
            else
                this.TaskTitle.text = "";
            end
        else
            this.nextController.selectedIndex = 0;
        end
        if taskTable.f_Award ~= "" then
            local award = decodeJsonStrToTabel(taskTable.f_Award);
            logicMgr.CostManager.RefreshItemList(this.listReward, award, nil, { isShowBigNum = true });
            this.listReward.width = 185 * #award;
        end
        this.nowTaskId = taskTable.f_TaskId;
        this.nowTaskStatus = taskData.status;
    end
    this.treasureController.selectedIndex = 0;
    local taskConfig = logicMgr.TaskManager.getRemarkShowDataByType(EnumConst.AchieveTaskType.Chapter);
    for k, v in pairs(taskConfig) do
        local serverData = logicMgr.TaskManager.getTaskServerData(v.f_TaskId);
        if serverData.status == 1 then
            this.treasureController.selectedIndex = 1;
            break ;
        end
    end
end

function UIBattle.onClickRewardTaskAward()
    if this.nowTaskId ~= nil then
        if this.nowTaskStatus == 1 then
            taskInfoHandler.SendReqTaskRewards(this.nowTaskId);
        else
            showUI(PanelNames.UIChapterReward);
        end
    end
end

--宠物buff加成
function this.petInit()
    --宠物资源Buff加成
    this.PetBuffShowIndex = 0
    this.PetEcoBuffInfoList = PetManager.GetPetEcoBuffList()
    if #this.PetEcoBuffInfoList > 0 then
        this.PetBuffShowIndex = 1
    end
    this.PetBuffShowController:SetSelectedIndex(this.PetBuffShowIndex)
end
function this.onClickPetBuffClose()
    this.PetBuffShowIndex = 1
    this.PetBuffShowController:SetSelectedIndex(this.PetBuffShowIndex)
end
function this.onClickPetBuff()
    if this.PetBuffShowIndex == 1 then
        this.PetBuffShowIndex = 2
        this.List_PetBuffAdd.numItems = #this.PetEcoBuffInfoList
    else
        this.PetBuffShowIndex = 1
    end
    this.PetBuffShowController:SetSelectedIndex(this.PetBuffShowIndex)
end
function this.itemRendererPetBuff(index, obj)
    local _index = index + 1
    obj:GetChild("icon").url = this.PetEcoBuffInfoList[_index].buffIcon
    obj:GetChild("info").text = getLanguage(this.PetEcoBuffInfoList[_index].buffDesc)
end
function this.UIBattleChapterRewardSuc(taskId,rewards)
    logicMgr.ItemFlyMgr.FlyRewards(rewards,this.listReward.xy)
end
function this.DoReconnect()
    taskInfoHandler.sendReqTaskMessage()
end

function this.CheckTheFunctionOpen(taskType)
    if this.main_task_open_cache == nil then
        this.main_task_open_cache = {}
        for k,v in pairs(this.mainTaskList[1]) do
            this.main_task_open_cache[v] = 0
        end
    end

    if this.main_task_open_cache[taskType] == 1 then
        return true
    else
        local index = 1
        for k,v in pairs(this.mainTaskList[1]) do
            if taskType == v then
                index = k
                break
            end
        end
    
        local tmp = this.mainTaskList[2][index]
        local open = logicMgr.FuncOpenManager.isOpen(tmp)
        this.main_task_open_cache[taskType] = open and 1 or 0
        return open
    end
end

function UIBattle.updateMainTask(id)
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.TaskMenu) then
        this.showTaskController.selectedIndex = 0;
        return;
    else
        this.showTaskController.selectedIndex = 1;
    end
    if id and this.nowMainTaskId ~= id then
        return;
    end
    local taskList = {};
    local taskDataList = logicMgr.TaskManager.getRemarkShowDataByType(EnumConst.AchieveTaskType.Main);
    for k, v in pairs(taskDataList) do
        for key, value in pairs(this.mainTaskList[1]) do
            TaskManager.getTaskServerData(v.f_TaskId)
            if v.f_TaskType == value and  this.CheckTheFunctionOpen(v.f_TaskType)  then
                if TaskManager.getTaskServerData(v.f_TaskId).status ~= -1 then
                    table.insert(taskList, v);
                end
            end
        end
    end
    if #taskList > 0 then
        this.showTaskController.selectedIndex = 1;
        math.randomseed(tostring(os.time()):reverse():sub(1, 7));
        local taskData = taskList[math.random(1, #taskList)];
        this.nowMainTaskId = taskData.f_TaskId;
        this.TaskDesc.text = getLanguage(taskData.f_TaskDesc)
        local td = TaskManager.getTaskServerDataById(taskData.f_TaskId)
        this.TaskNum.text = table.concat({"(",td.progress, "/", taskData.f_Progress, ")"})

        this.TaskReward:ResizeToFit();
        this.TaskReward.visible = false;
        this.taskOpen.visible = true;
    else
        this.showTaskController.selectedIndex = 0;
    end
end
function UIBattle.onClickGoMainTask()
    showUI(PanelNames.UITaskInfo, EnumConst.TaskType.achievementTask);
end
function UIBattle.onClickMainTask()
    ListenEvent(Config.EventType.TouchAnyKey, this.onClickMainTaskClose);
    this.taskOpen.visible = false;
    this.TaskReward.visible = true;
end
function UIBattle.onClickMainTaskClose()
    CloseEvent(Config.EventType.TouchAnyKey, this.onClickMainTaskClose);
    this.taskOpen.visible = true;
    this.TaskReward.visible = false;
end
function UIBattle.onClickChapterReward()
    showUI(PanelNames.UIChapterRewardNew);
end
---英雄组合
function UIBattle.onClickBattleRecommend()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BattleRecommend, true, this.btnBattleRecommend) then
        showUI(PanelNames.UIBattleRecommend);
    end
end
function UIBattle.UILayerMaskChanged(uiPath,isShow)
    if uiPath ~= PanelNames.UIBattle then return end
    if isShow then
        if this.uiBattleBGMap then
            this.uiBattleBGMap:OnEnable()
        end
        if this.cameraMain then
            this.cameraMain.enabled = true
        end
    else
        if this.uiBattleBGMap then
            this.uiBattleBGMap:OnDisable()
        end
        if this.cameraMain then
            this.cameraMain.enabled = false
        end
    end
end
function UIBattle.Refresh_ChangePlunderFunction()
    this.ctrlRobOpen.selectedIndex = plunderHandler.change_plunder_function_type
end
function UIBattle.Refresh_PlunderInfo()
    this.Refresh_ChangePlunderFunction()
end
--突袭开关
function UIBattle.Refresh_OpenPlunder(isShow)
    if this.robListPanel then
        this.ctrlShowRobList.selectedIndex = isShow and 1 or 0
        if isShow then
            this.robListPanel:Open()
        end
        this.Refresh_ChangePlunderFunction()
    end
end

--主线助力
function UIBattle.RefreshDungeonRandomEvent()
    this.removeRandomEventTimer();
    if logicMgr.DungeonRandomEventManager.hasDungeonRandomEventData() then
        this.randomCtrl.selectedIndex = 1;
        this.randomEventTimeCount = logicMgr.DungeonRandomEventManager.getDungeonRandomEventDataEndTime() - HelperFunc.GetServerTime();

        this.dungeonRandomEventTimeCount();
        this.randomEventTimer = utimer.timeCall(this.dungeonRandomEventTimeCount, 1000, -1);
    else
        this.randomCtrl.selectedIndex = 0;
    end
end

function UIBattle.dungeonRandomEventTimeCount()
    this.randomEventTimeCount = this.randomEventTimeCount - 1;
    if this.randomEventTimeCount < 0 then
        this.randomCtrl.selectedIndex = 0;
        this.removeRandomEventTimer();
        return;
    end
    this.TextRandomEventTime.text = timeToTimeFormat(this.randomEventTimeCount);
end

function UIBattle.removeRandomEventTimer()
    if this.randomEventTimer then
        utimer.remove(this.randomEventTimer);
        this.randomEventTimer = nil
    end
end

function UIBattle.onClickRandomEvent()
    logicMgr.DungeonRandomEventManager.OpenDungeonRandomEventUI();
end

function UIBattle.WaitingBattleFinishedPopUpMsg(isWaiting)
    this.isWaitingBattleFinishedPopUp = isWaiting
end

--- 看板娘
function UIBattle.refreshSideGirl()
    local normalId, hardId = HeroManager.getShowFemaleRole(), HeroManager.getShowTravelFemaleRole()
    local cfgNormal = dataTable.getDataTableByStringId("t_sidegirl", tostring(normalId))
    if cfgNormal then
        local pos = decodeJsonStrToTabel(cfgNormal.f_ImgXy)
        this.normalSideGirl.url = cfgNormal.f_SpinePath
        this.normalSideGirl.x = this.normalSideGirlOriginPos[1] + tonumber(pos[1])
        this.normalSideGirl.y = this.normalSideGirlOriginPos[2] + tonumber(pos[2])
    end
    local cfgHard = dataTable.getDataTableByStringId("t_sidegirl", tostring(hardId))
    if cfgHard then
        local pos = decodeJsonStrToTabel(cfgHard.f_ImgXy)
        this.hardSideGirl.url = cfgHard.f_SpinePath
        this.hardSideGirl.x = this.hardSideGirlOriginPos[1] + tonumber(pos[1])
        this.hardSideGirl.y = this.hardSideGirlOriginPos[2] + tonumber(pos[2])
    end
end

return UIBattle